import http.client
import urllib.parse
import json
import os


'''
curl -d "IMEI=358688000000100&LANG=en-US&BB_CHIPSET=6235B&JOY_VE_VERS=3.0.1
&RES_LANDSCAPE=320x240&RES_PORTRAIT=240x320&TV_LANDSCAPE=320x240
&TV_PORTRAIT=240x180&MCC_COUNTRY=460&IDH=TLG
&IMSI=9466970701492096,9466970701492096
&ICCID=89886970205072101022,89886970205072101022
&AVAIL_STORAGE=125MB"  http://sandbox.gabbit.com/v1/device.json
'''

host = "sandbox.gabbit.com"

id_device = ''
group_device=''
manifest_dir ="d:\\test\\"
src_width=220
src_height=176



def register_phone():
    '''
    register the phone
    '''
    global id_device
    global group_device
    res_landscape=src_width
    res_portrait=src_height
    tv_landscape=src_height
    tv_portrait=src_height*3/4
    params = urllib.parse.urlencode({'IMEI':'358688000000100',
                                     'LANG':'en-US',
                                     'BB_CHIPSET':'6235B',
                                     'JOY_VE_VERS':'3.0.1',
                                     'RES_LANDSCAPE':"{0}x{1}".format(res_landscape,res_portrait),
                                     'RES_PORTRAIT':"{1}x{0}".format(res_landscape,res_portrait),
                                     'TV_LANDSCAPE':"{0}x{1}".format(res_landscape,res_portrait),
                                     'TV_PORTRAIT':"{1}x{0}".format(tv_landscape,tv_portrait),
                                     'MCC_COUNTRY':'460',
                                     'IDH':'TLG',
                                     'IMSI':'9466970701492096,9466970701492096',
                                     'ICCID':'89886970205072101022,89886970205072101022',
                                     'AVAIL_STORAGE':'12500'
                                     })                                   
    conn = http.client.HTTPConnection(host)
    conn.request("POST", "/v1/device.json", params)
    r1 = conn.getresponse()
    data=r1.read()
    data = data.decode('utf-8')
    ret= json.loads(data)
    if ('device' in ret):
        device = ret['device']
        id_device = device['id']
        group_device = device['group']
    else:
        print("register wrong")
        print(ret)



def download_image_file(str_url):
    '''
    download the file and save it into the url last part.
    '''
    print(str_url)
    str_list = str_url.split('/')
    filename = str_list[len(str_list) -1]
    conn = http.client.HTTPConnection(host)
    conn.request("GET", str_url)
    r1 = conn.getresponse()
    data = r1.read()
    # save the manifest file
    f = open(manifest_dir + filename,"wb")
    f.write(data)
    f.close()




def download_ad(ad):
    if( 'assets' in ad):
        assets = ad['assets']
        if( 'portrait' in assets):
            #print('portrait')
            portrait = assets['portrait']
            for i in portrait:
                if( 'url' in i):
                    url = i['url']
                    download_image_file(url)
        if( 'landscape' in assets):
            #print('landscape')
            portrait = assets['landscape']
            for i in portrait:
                if( 'url' in i):
                    url = i['url']
                    download_image_file(url)



            


def download_channel(channel):
    if( 'ads' in channel):
        ads = channel['ads']
        for item in ads:
            download_ad(item)





def download_manifest(manifest):
    '''
    download the manifest
    '''
    print('begin to download es-post images')
    if( 'es-post' in manifest):
        es_post = manifest['es-post']
        for item in es_post :
            download_channel(item)
    else:
        print('no es-post')
    print('begin to download es-pre images')
    if( 'es-pre' in manifest):
        es_pre = manifest['es-pre']
        for item in es_pre :
            download_channel(item)
    else:
        print('no es-pre')
    print('begin to download splash images')
    if( 'splash' in manifest):
        splash = manifest['splash']
        download_channel(splash)





'''
curl "http://sandbox.gabbit.com/v1/device_group/b31c899f51f4a4e8d6d164b18dc3ac3
064544019/manifest.json?device_id=7f086708-cc37-4b49-a642-2accf98f0d16&AVAIL_ST
ORAGE=20000&BLOCK_SIZE=4096"
'''
def get_manifest(dev_id, group):
    manifest_url = "/v1/device_group/"
    manifest_url += group
    manifest_url +="/manifest.json?device_id="
    manifest_url +=dev_id
    manifest_url +="&AVAIL_STORAGE=20000&BLOCK_SIZE=4096"
    conn = http.client.HTTPConnection(host)
    conn.request("GET", manifest_url)
    r1 = conn.getresponse()
    data = r1.read()
    print("download manifest complete")
    # save the manifest file
    f = open(manifest_dir + "manifest.txt","wb")
    f.write(data)
    f.close()
    print("save manifest complete")

    data = data.decode('utf-8')
    ret = json.loads(data)
    if('error' in ret):
        print("Get manifest wrong")
        err = ret['error']
        code = err['code']
        print(code)
    else:
        print("ok")
        if( 'manifest' in ret):
            manifest = ret['manifest']
            download_manifest(manifest)
            
        
        
    
    


if __name__=="__main__":
    print("start")
    register_phone()
    print("device id: "+id_device)
    print("group  id:"+group_device)
    #id_device = "7f086708-cc37-4b49-a642-2accf98f0d16"
    #group_device="b31c899f51f4a4e8d6d164b18dc3ac3064544019"
    get_manifest(id_device, group_device)
    #download_image_file("http://static.sandbox.gabbit.com/uploads/436c7107-ffe5-4d54-8521-2a8742e734f4.jpg")
    print("complete")
	



